<template>
  <view class="container">
    <scroll-view scroll-y="true" class="agent_info">
      <view style="padding-bottom: 50rpx">
        <view class="user-info">
          <img :src="aiInfo.avatarUrl" class="user-img" />
          <uni-icons
            class="add-avatar"
            type="plus-filled"
            color="#0092FF"
            size="40"
            @click="chooseFile"
          />
        </view>
        <view class="easy_create_btn">
          <up-button
            type="primary"
            text="一键完善"
            plain
            @tap="openHelp"
          ></up-button>
        </view>
        <view class="form-item name">
          <view class="title">名称</view>
          <input
            cursor-spacing="100"
            placeholder="智能体名称"
            v-model="aiInfo.nickname"
          />
        </view>
        <view class="form-item">
          <view class="title">设定描述</view>
          <textarea
            :disable-default-padding="true"
            cursor-spacing="100"
            v-model="aiInfo.agentDescription"
            placeholder="示例：你是一位经验丰富的英语老师，拥有激发学生学习热情的教学方法。你善于运用幽默和实际应用案例，使对话充满趣味。"
          />
        </view>
        <view class="form-item">
          <view class="title">设定开场白</view>
          <textarea
            :disable-default-padding="true"
            cursor-spacing="100"
            v-model="aiInfo.prologue"
            placeholder="将作为开启聊天的第一句话"
          />
        </view>
        <view class="form-card">
          <view class="form-card-item" style="border: 0 none">
            <view class="title">语言</view>
            <view class="text" @tap="showPicker('language')">
              <view>{{ pickerData.languageName || "请选择" }}</view>
              <uni-icons type="right" size="16" style="margin-left: 20rpx" />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title">性别</view>
            <view class="text" @tap="showPicker('sex')">
              <view>{{ pickerData.sexName || "请选择" }}</view>
              <uni-icons type="right" size="16" style="margin-left: 20rpx" />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title">声音</view>
            <view class="text" @tap="showPicker('voice')">
              <view>{{ aiInfo.voiceName || "请选择" }}</view>
              <uni-icons type="right" size="16" style="margin-left: 20rpx" />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title">公开性</view>
            <view class="text" @tap="showPicker('isOpen')">
              <view>{{ pickerData.isOpenName || "请选择" }}</view>
              <uni-icons type="right" size="16" style="margin-left: 20rpx" />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title" style="width: 30%">对话风格</view>
            <view class="text">
              <input
                cursor-spacing="100"
                placeholder="例：甜美风"
                v-model="aiInfo.languageStype"
              />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title" style="width: 30%">技能</view>
            <view class="text">
              <input
                cursor-spacing="100"
                placeholder="例：唱歌"
                v-model="aiInfo.skills"
              />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title" style="width: 30%">口头禅</view>
            <view class="text">
              <input
                cursor-spacing="100"
                placeholder="例：嗯嗯"
                v-model="aiInfo.petPhrase"
              />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title">爱好</view>
            <view class="text" @tap="showPickerCustom('hobby')">
              <view>{{ translateText("hobby") || "请选择" }}</view>
              <uni-icons type="right" size="16" style="margin-left: 20rpx" />
            </view>
          </view>
          <view class="form-card-item">
            <view class="title">职业</view>
            <view class="text" @tap="showPickerCustom('career')">
              <view>{{ translateText("career") || "请选择" }}</view>
              <uni-icons type="right" size="16" style="margin-left: 20rpx" />
            </view>
          </view>
        </view>
        <button type="primary" class="save" @tap="saveAI">保存智能体</button>
      </view>
      <u-picker
        v-if="pickerShow"
        :show="pickerShow"
        :columns="columns"
        keyName="showName"
        :defaultIndex="defaultIndex"
        @confirm="pickerConfirm"
        @cancel="pickerShow = false"
      ></u-picker>
    </scroll-view>
    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog
        type="info"
        mode="base"
        title="一键完善智能体"
        confirmText="生成配置"
        :beforeClose="true"
        @close="$refs.popup.close()"
        @confirm="getAgentConfig"
      >
        <view class="popup-content">
          <up-textarea
            style="width: 100%"
            v-model="easyCreateText"
            placeholder="请对智能体进行简要描述"
            :cursorSpacing="100"
            :disableDefaultPadding="true"
          ></up-textarea>
        </view>
      </uni-popup-dialog>
    </uni-popup>
    <Tabbar :current="1" :tab-bar-list="tabBerLists" />
    <popupTag @confirmData="getTagsContet" :tasgData="tasgData" />
  </view>
</template>

<script setup>
import arr from "@/utils/tabbar";
import popupTag from "./coms/popupTag.vue";
import {
  createAgent,
  getAgentAttr,
  getVoiceAttr,
  initAgentAttr,
} from "@/global/agentApi";

const { proxy } = getCurrentInstance();
let tabBerLists = ref(arr);
let aiInfo = ref({
  avatarUrl:
    "https://img1.baidu.com/it/u=1440367729,4287830518&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=667",
  nickname: "",
  agentDescription: "",
  languageCode: "34",
  userId: uni.getStorageSync("currentUserId"),
  voiceId: "",
  voiceName: "",
  sexCode: "",
  prologue: "",
  isOpenCode: "",
  type: "default",
});
let pickerData = reactive({
  languageName: "中文",
  isOpenName: "",
  sexName: "",
  hobbyName: "",
  careerName: "",
  voiceList: [],
  sexList: [],
  languageList: [],
  isOpenList: [],
  hobbyList: [],
  careerList: [],
});
let columns = ref([]);
let defaultIndex = ref([0]);
let pickerShow = ref(false);
let pickerType = ref("");
let easyCreateText = ref("");

//传入到popupTags组件的数据
const tasgData = ref({
  tagsList: [], //tag列表
  tagsFlag: false, //是否展示popup
  tagsContent: "", //输入框
  tagsChecked: [], //默认选中的
});

const getAgentConfig = () => {
  if (easyCreateText.value == "") {
    uni.showToast({
      title: "请填写简要描述",
      icon: "none",
    });
    return;
  }
  uni.showLoading({
    title: "生成中...",
  });
  initAgentAttr({ content: easyCreateText.value })
    .then((res) => {
      uni.hideLoading();
      if (res && res.code == 200) {
        aiInfo.value = { ...aiInfo.value, ...res.data };
        console.log(aiInfo.value);
        easyCreateText.value = "";
        proxy.$refs.popup.close();
      }
    })
    .catch(() => {
      uni.hideLoading();
    });
};

const openHelp = () => {
  easyCreateText.value = "";
  proxy.$refs.popup.open();
};

//自定义的弹框选项（多选tag和输入框） 打开
const showPickerCustom = (type) => {
  pickerType.value = type;
  tasgData.value.tagsList = pickerData[`${type}List`];
  tasgData.value.tagsFlag = true;
  tasgData.value.tagsChecked = aiInfo.value[`${pickerType.value}`] || [];
  tasgData.value.tagsContent = aiInfo.value[`${type}Customize`];
};

//确认事件
const getTagsContet = (data) => {
  console.log(pickerType.value);
  tasgData.value.tagsFlag = false;
  aiInfo.value[`${pickerType.value}`] = data.tagsChecked;
  aiInfo.value[`${pickerType.value}Customize`] = data.tagsContent;
  console.log(aiInfo.value);
};

//弹框tag选中和输入框后转文字展示
const translateText = (key) => {
  let str = "";
  let checkedList = aiInfo.value[`${key}`]; //已选中的tag集合
  if (checkedList) {
    checkedList.map((name, index) => {
      str += name + (index === checkedList.length - 1 ? "" : ",");
    });
    return (
      str +
      (aiInfo.value[`${key}Customize`]
        ? (str ? "," : "") + aiInfo.value[`${key}Customize`]
        : "")
    );
  }
  return "";
};

const showPicker = (type) => {
  pickerType.value = type;
  columns.value = [pickerData[`${type}List`]];
  let key = "";
  switch (type) {
    case "voice":
      key = "voiceId";
      break;
    default:
      key = `${type}Code`;
      break;
  }
  if (aiInfo.value[key]) {
    for (let index in pickerData[`${type}List`]) {
      if (pickerData[`${type}List`][index].dictCode === aiInfo.value[key]) {
        defaultIndex.value = [+index];
        break;
      }
    }
  } else {
    defaultIndex.value = [0];
  }
  pickerShow.value = true;
};

const pickerConfirm = (val) => {
  let key = "";
  switch (pickerType.value) {
    case "voice":
      key = "voiceId";
      break;
    default:
      key = `${pickerType.value}Code`;
      break;
  }
  aiInfo.value[key] = val.value[0].dictCode;
  if (pickerType.value === "voice") {
    aiInfo.value.voiceName = val.value[0].showName;
  } else {
    pickerData[`${pickerType.value}Name`] = val.value[0].showName;
  }
  pickerShow.value = false;
};

const saveAI = () => {
  if (!aiInfo.value.nickname) {
    uni.showToast({
      title: `昵称不能为空,请输入昵称`,
      icon: "none",
      duration: 2000,
    });
    return;
  }
  if (!aiInfo.value.agentDescription) {
    uni.showToast({
      title: `描述不能为空,请输入描述`,
      icon: "none",
      duration: 2000,
    });
    return;
  }
  aiInfo.value.userId = uni.getStorageSync("currentUserId");
  createAgent(aiInfo.value).then((res) => {
    if (res.code === 200) {
      global.tabBarCurrent = 2;
      aiInfo.value = {
        avatarUrl:
          "https://img1.baidu.com/it/u=1440367729,4287830518&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=667",
        nickname: "",
        agentDescription: "",
        languageCode: "34",
        userId: uni.getStorageSync("currentUserId"),
        voiceId: "",
        voiceName: "",
        sexCode: "",
        prologue: "",
        isOpenCode: "",
        type: "default",
      };
      pickerData = reactive({
        languageName: "中文",
        isOpenName: "",
        sexName: "",
        hobbyName: "",
        careerName: "",
        voiceList: [],
        sexList: [],
        languageList: [],
        isOpenList: [],
        hobbyList: [],
        careerList: [],
      });
      uni.switchTab({
        url: "/pages/index/user",
      });
    }
  });
};

const chooseFile = () => {
  uni.chooseImage({
    count: 1,
    mediaType: ["image"],
    sizeType: ["compressed"],
    camera: "back",
    success: (res) => {
      let baseUrl = import.meta.env.VITE_APP_BASE_API_CHAT;
      aiInfo.value.avatarUrl = res.tempFilePaths[0];
      uni.showLoading({
        title: "加载中",
      });
      uni.uploadFile({
        url: baseUrl + "/chatmgt/app/avatar",
        filePath: res.tempFiles[0].path || "",
        name: "avatarFile",
        formData: {},
        headers: { "Content-Type": "multipart/form-data" },
        success: (uploadFileRes) => {
          if (uploadFileRes && uploadFileRes.errMsg == "uploadFile:ok") {
            uni.hideLoading();
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "error",
              title: uploadFileRes.errMsg,
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            icon: "error",
            title: JSON.stringify(err),
          });
          console.log("图片上传接口调用失败", err);
        },
      });
    },
  });
};

onLoad(() => {
  uni.hideTabBar();
  getAgentAttr().then((res) => {
    pickerData.languageList = res.data.languageList;
    pickerData.sexList = res.data.sexList;
    pickerData.isOpenList = res.data.isOpenList;
    pickerData.hobbyList = res.data.hobbyList;
    pickerData.careerList = res.data.careerList;
  });
  getVoiceAttr().then((res) => {
    pickerData.voiceList = res.rows.map((item) => {
      item.showName = item.voiceName;
      item.dictCode = item.voiceId + "";
      return item;
    });
  });
});
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}
</style>
